package com.syj.collect.Present;

import android.util.Log;
import android.widget.EditText;


import com.amap.api.maps.model.Marker;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.syj.collect.base.BasePresent;
import com.syj.collect.entry.KeyvalueBean;
import com.syj.collect.entry.StationDetailBean;
import com.syj.collect.entry.StationPointBean;
import com.syj.collect.entry.TagAdapterData;
import com.syj.collect.entry.TaskBean;
import com.syj.collect.entry.UserInfoBean;
import com.syj.collect.entry.WaterColorBean;
import com.syj.collect.http.BaseObserver;
import com.syj.collect.http.BaseRequest;
import com.syj.collect.utils.SPUtil;
import com.syj.collect.view.CHomeView;
import com.syj.collect.view.LoginView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static cn.hutool.http.ContentType.JSON;

public class CHomePresent extends BasePresent<CHomeView> {


    public void getStationList() {
        Gson gson = new Gson();
        UserInfoBean.UserInfo gsb = gson.fromJson(SPUtil.getPrefString("userInfo", ""), UserInfoBean.UserInfo.class);

        BaseRequest.getInstance().getApiServise().getStationList(gsb.getUserId() + "", SPUtil.getPrefString("token", ""))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("station", value);

                        Gson gson = new Gson();
                        StationPointBean gbean = gson.fromJson(value, StationPointBean.class);
                        if (gbean.getCode() == 0) {
                            view.initgetStationSuccess(gbean.getData());
                        } else {
                            view.initFail(gbean.getMsg());
                        }


                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }

    public void getStationData(Marker str) {
        Log.e("station", str.getObject() + "");
        BaseRequest.getInstance().getApiServise().getDataByCode(str.getTitle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("station", value);
                        Gson gson = new Gson();
                        StationDetailBean gbean = gson.fromJson(value, StationDetailBean.class);
                        if (gbean.getCode() == 0) {
                            view.initSuccess(gbean.getData(), str);
                        } else {
                            view.initFail(gbean.getMsg());
                        }


                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }

    public void getTagDate() {
        BaseRequest.getInstance().getApiServise().getWaterList("030001", SPUtil.getPrefString("token", ""))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
                        Gson json = new Gson();
                        TagAdapterData result = json.fromJson(value, TagAdapterData.class);
                        // JSONObject jsonObject = new JSONObject(value);
//                        Log.e("tag结果 :", value);
                        // JSONArray msg = jsonObject.getJSONArray("data");
                        int code = result.getCode();
                        if (code == 0) {
                            view.initTagSuccess(result.getData());
                        } else {
                            view.initFail(result.getMsg());
                        }

                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }

    public void getWaterColor() {
        BaseRequest.getInstance().getApiServise().getWaterList("030002", SPUtil.getPrefString("token", ""))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
                        Gson json = new Gson();

                        WaterColorBean result = json.fromJson(value, WaterColorBean.class);
                        // JSONObject jsonObject = new JSONObject(value);
//                        Log.e("water结果 :", value);
                        // JSONArray msg = jsonObject.getJSONArray("data");
                        int code = result.getCode();
                        if (code == 0) {
                            view.initColorSuccess(result.getData());
                        } else {
                            view.initFail(result.getMsg());
                        }

                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }


    public void saveDate(boolean isSave, String stationCode, List<String> string, List<KeyvalueBean> date, String water, String supplyMsg, WaterColorBean.WaterColor selectSpinner) {
        HashMap hashMap = new HashMap();
        Gson gson = new Gson();
        UserInfoBean.UserInfo gsb = gson.fromJson(SPUtil.getPrefString("userInfo", ""), UserInfoBean.UserInfo.class);
        //hashMap.put("id", );//修改时用
        hashMap.put("addMsg", "" + supplyMsg);//补充信息
        //hashMap.put("auditMsg", "无");//审核意见
        hashMap.put("anionic", "" + date.get(1).getValue());//阴离子表面活性
        //hashMap.put("auditStatus", ""+0);//0 2 3  未  通过  未通过
        hashMap.put("cod", "" + date.get(0).getValue());//化学量
        hashMap.put("fileIds", string);
        hashMap.put("nh3", date.get(4).getValue());//氨氮
        hashMap.put("pollutionStatus", "" + water);//污染状况
        hashMap.put("isSubmit", isSave ? "" + 0 : "" + 1);//1,0
        hashMap.put("stationCode", "" + stationCode);//站点编号
        hashMap.put("tn", "" + date.get(3).getValue());//总氮
        hashMap.put("tp", "" + date.get(2).getValue());//总磷
        //hashMap.put("reportDate", "");
        hashMap.put("createBy", "" + gsb.getUserId());//创建人id
        String str =selectSpinner.getLabel() + ";" + selectSpinner.getDescription() ;
        hashMap.put("remarks", "" + str);//水体色
        Gson gson1 = new Gson();
        Log.e("param :", gson1.toJson(string));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson1.toJson(hashMap));
        BaseRequest.getInstance().getApiServise().saveDate(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
                        try {
                            JSONObject jsonObject = new JSONObject(value);
//                            Log.e("Interceptor1结果 :", value);
                            String msg = jsonObject.getString("data");//{"msg":"success","code":0,"data":"新增成功！"} 还中文了
                            int code = jsonObject.getInt("code");
                            if (code == 0) {
                                view.initSuccess(msg);
                            } else {
                                view.initFail(msg);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }

    ;

    public void upLoadFiles(boolean isSave, String stationCode, List<String> imgs, List<KeyvalueBean> date, String water, String supplyMsg, WaterColorBean.WaterColor selectSpinner) {
        //upLoadFile(imgs.get(0));
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (int i = 0; i < imgs.size(); i++) {

            Log.e("files", imgs.get(i));

            File file = new File(imgs.get(i));
            // create RequestBody instance from file
            MultipartBody.Part part = MultipartBody.Part.createFormData("files", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
            MultipartBody.Part part1 = MultipartBody.Part.createFormData("describes", file.getName()/*, RequestBody.create(MediaType.parse("text/plain"), file.getName())*/);
            builder.addPart(part);
            builder.addPart(part1);

        }
        MultipartBody multipartBody = builder.build();
        BaseRequest.getInstance().getApiServise().saveImg(multipartBody).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("files", value);

                        try {
                            JSONObject jsonObject = new JSONObject(value);
//                            Log.e("结果 :", value);
                            String msg = jsonObject.getString("msg");
                            int code = jsonObject.getInt("code");
                            if (code == 0) {
                                //view.initSuccess(msg);
                                JSONArray old = jsonObject.getJSONObject("data").getJSONArray("ids");
                                List list = new ArrayList<>();
                                for (int i = 0; i < imgs.size(); i++) {
                                    list.add(old.get(i));
                                }
                                saveDate(isSave, stationCode, list, date, water, supplyMsg, selectSpinner);
//                                Log.e("ooooooo", stationCode + "  " + old);
                            } else {
                                view.initFail(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
//                        Log.e("files", e.toString());
                        view.initFail(e.toString());
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }

    public void upLoadFile(String str) {

        File file = new File(str);
        // create RequestBody instance from file
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        RequestBody des = RequestBody.create(MediaType.parse("multipart/form-data"), file.getName());
        //describe
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        // builder.addPart(part);

        BaseRequest.getInstance().getApiServise().upLoadnormImg(part, des).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("files", value);

                        try {
                            JSONObject jsonObject = new JSONObject(value);
//                            Log.e("结果 :", value);
                            String msg = jsonObject.getString("msg");
                            int code = jsonObject.getInt("code");
                            if (code == 0) {
                                //view.initSuccess(msg);

                            } else {
                                view.initFail(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
//                        Log.e("files", e.toString());
                        view.initFail(e.toString());
                    }

                    @Override
                    public void onEnd() {
//                        Log.e("files", "end");
                    }
                });
    }

    public void getTaskList1() {
        HashMap hashMap = new HashMap();
        Gson gson = new Gson();
        UserInfoBean.UserInfo gsb = gson.fromJson(SPUtil.getPrefString("userInfo", ""), UserInfoBean.UserInfo.class);

        hashMap.put("status", "1");//1 未采集  2采集中  3已采集
        hashMap.put("userId", gsb.getUserId());
        hashMap.put("grade", "2");//1常规  2紧急
        //hashMap.put("endTime", "");
        //hashMap.put("startTime", "");


//        String md5string=StringUtils.initString(hashMap);
//        hashMap.put("sign",md5string);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(hashMap));
        BaseRequest.getInstance().getApiServise().getUserTask1(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("task结果?", value);
                        Gson gson = new Gson();
                        TaskBean gBean = gson.fromJson(value, TaskBean.class);

                        if (gBean.getCode() == 0) {
                            view.initTaskSuccess(gBean.getData().getTotalCount(), gBean.getData().getList());
                        } else {
                            view.initFail(gBean.getMsg());
                        }

                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }


}
